package com.example.administrator.shzs.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Looper;
import android.util.Log;

import com.example.administrator.shzs.activity.MainActivity;
import com.example.administrator.shzs.activity.WelcomeActivity;
import com.example.administrator.shzs.app.MyApplication;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局捕获异常
 */
public class CrashHandler implements UncaughtExceptionHandler {


	private MyApplication app;

	//用来存储设备信息和异常信息
	private Map<String, String> infos = new HashMap<String, String>();

	//用于格式化日期,作为日志文件名的一部分
	private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

	public CrashHandler(MyApplication app){
		this.app=app;
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {

		//收集设备信息
		String mobileInfo  = getMobileInfo();
		//获取错误信息
		String errorinfo = getErrorInfo(ex);

		Log.e("Life","崩溃信息"+errorinfo);
		Log.e("Life","手机型号"+mobileInfo);


		new Thread() {
			public void run() {
				// 创建loop
				Looper.prepare();
				ToastUtils.showMessageLong(app,"抱歉，由于手机兼容性问题导致程序出现异常，即将重启");
				//开始处理消息
				Looper.loop();
			}
		}.start();


		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}


		//实现重启
		AlarmManager manager = (AlarmManager) app.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(app, WelcomeActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra("crash", true);
		PendingIntent restartIntent = PendingIntent.getActivity(app, 0, intent, PendingIntent.FLAG_ONE_SHOT);
		manager.set(AlarmManager.RTC, System.currentTimeMillis() + 1200, restartIntent); // 1秒钟后重启应用

		app.finishActivity();
		System.exit(0);
		System.gc();
	}


	/**
	 * 获取错误的信息
	 * @param arg1
	 * @return
	 */
	private String getErrorInfo(Throwable arg1) {
		Writer writer = new StringWriter();
		PrintWriter pw = new PrintWriter(writer);
		arg1.printStackTrace(pw);
		pw.close();
		String error= writer.toString();
		return error;
	}


	/**
	 * 获取手机的硬件信息
	 * @return
	 */
	private String getMobileInfo() {

		String device_model=Build.MODEL;

		String version_release=Build.VERSION.RELEASE;//系统版本
		return device_model+"\n系统版本"+version_release;
	}


}
